package demo1;

import java.util.Arrays;
import java.util.Scanner;

public class 数组扩容 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int[] arr = {1,2,3};
        while (true){
            System.out.println("现有数组arr如下");
            for (int i = 0; i < arr.length; i++) {
                System.out.print(arr[i]+"\t");
            }
            System.out.println();
            System.out.println("是否要给数组扩容？y/n");
            String next = sc.next();
            if(next.equals("y")){
                //扩容
                System.out.println("请输入要添加的整数元素");
                int numAdd = sc.nextInt();
                int[] arr2 = new int[arr.length+1];
                for (int i = 0; i < arr.length; i++) {
                    arr2[i] = arr[i];
                }
                arr2[arr.length] = numAdd;
                //原有的arr数组给它替换成arr2，让它回收
                arr = arr2;
                //输出
                System.out.println("这是扩容后的数组");
                for (int i = 0; i < arr2.length; i++) {
                    System.out.print(arr2[i]+"\t");
                }
                System.out.println("\n=============");
            }else {
                break;
            }

        }
    }
}
